<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item :label="timeName" prop="time">
            <el-date-picker
              v-model="formData.time"
              type="datetime"
              :placeholder="'请输入' + timeName"
              :clearable="true"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="ElderVisitTime" lang="ts">
import { ElderVisitStatusEnum } from '@/utils/constants'
import * as ElderVisitApi from '@/api/elder/visit'
let visitId = 0
let visitType = 0
const message = useMessage()
const timeName = ref('')
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref({
  time: ''
})
const formRules = reactive({
  time: [
    {
      required: true,
      message: '请输入' + timeName.value,
      trigger: 'blur'
    }
  ]
})
/** 打开弹窗 */
const open = (id: number, type: number, visitTime: string) => {
  dialogVisible.value = true
  dialogTitle.value
  resetForm()
  visitId = id
  visitType = type
  if (type == ElderVisitStatusEnum.LEAVE) {
    timeName.value = '离开时间'
  } else {
    formData.value.time = visitTime
    timeName.value = '来访时间'
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const resetForm = () => {
  formData.value = {
    time: ''
  }
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    await ElderVisitApi.updateStatus({ id: visitId, status: visitType, time: formData.value.time })
    message.success('操作成功')
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
